from django.shortcuts import render

# Create your views here.
from django.http.response import JsonResponse
from   QQLoginTool.QQtool import OAuthQQ
from django.views import View

class QQLoginView(View):

    def get(self,request):

        code = request.GET.get('code')

        if code is None:
            return JsonResponse({'code':400,'errmsg':'没有参数'})
        # 申请的客户端id
        QQ_CLIENT_ID = '101474184'
        #申请的客户端秘钥
        QQ_CLIENT_SECRET = 'c6ce949e04e12ecc909ae6a8b09b637c'
        # 登陆成功后返回的路径
        QQ_REDIRECT_URI = 'http://www.meiduo.site:8080/oauth_callback.html'

        qq = OAuthQQ(client_id=QQ_CLIENT_ID,
                     client_secret=QQ_CLIENT_SECRET,
                     redirect_uri=QQ_REDIRECT_URI,
                     state='lalala')

        toke = qq.get_access_token(code)

        openid = qq.get_open_id(toke)


        #判断openid 是否存在
        from apps.oauth.models import OAuthQQUser
        #获取
        try:
            qquser = OAuthQQUser.objects.get(openid=openid)         #判断字段openid里是否存在
        except OAuthQQUser.DoesNotExist:
            #不存在openiid 返回让用户绑定
            from apps.oauth.itsdangerous import generic_open_id     #对导入itsdangerous的加密方法
            secret_openid = generic_open_id(openid)                 #对openid 进行加密
            #未绑定过，已响应的方式给前段界面
            return JsonResponse({'code':300,'access_token':secret_openid})
        else:
            #存在，让用户自行登录(状态保持)
            from django.contrib.auth import login
            # login 的第二个参数 应该是 User 模型的实例对象
            # qquser.属性
            # OAuthQQUser 有 user 的属性
            login(request,qquser.user) # qquser.user 就是User 的实例对象

            # 设置cookie
            response = JsonResponse({'code':0,'errmsg':'ok'})

            response.set_cookie('username',qquser.user.username,max_age=14*24*3600)

            return response

############################################qq绑定功能
    def post(self,request):
        import json
        data = json.loads(request.body.decode())

        mobile = data.get('mobile')
        password = data.get('password')
        sms_code = data.get('sms_code')
        secret_data = data.get('access_token')

        from apps.oauth.itsdangerous import check_open_id     # 导入itsdangerous的解密方法
        openid = check_open_id(secret_data)                     #解密
        if openid is None:
            return JsonResponse({'code':400,'errmsg':'参数错误'})
        #验证参数，手机号，密码，验证码
        import re
        if not re.match('1[3-9]{9}',mobile):
            return JsonResponse({'code': 400, 'errmsg': '手机号错误'})
        if not re.match('[a-zA-Z_0-9-]{5,20}', password):
            return JsonResponse({'code': 400, 'errmsg': '密码格式错误'})
        if not re.match('[0-9]{6}', sms_code):
            return JsonResponse({'code': 400, 'errmsg': '短信格式错误'})


        #验证短信验证码
        from django_redis import get_redis_connection
        redis_cli = get_redis_connection('code')                  #链接数据库

        redis_sms_code = redis_cli.get(mobile)                      # 获取短信 bytes 类型

        if redis_sms_code is None:
            return JsonResponse({'code':400,'errmsg':'短信验证码过期'})
        if redis_sms_code.decode() != sms_code:
            return JsonResponse({'code':400,'errmsg':'短信验证码错误'})
        # 根据手机号判断用户信息
        from apps.users.models import User
        try:
            user = User.objects.get(mobile=mobile)  #判断mobile字段里 是否有手机号
        except User.DoesNotExist:
            #没有查询到,创建一个新用户
            user = User.objects.create_user(username=mobile,mobile=mobile,password=password)
        else:
            #查询到了，验证密码
            if not user.check_password(password):
                return JsonResponse({'code':400,'errmsg':'手机号或密码不正确,绑定失败'})

        #绑定用户信息。数据入库

        from apps.oauth.models import OAuthQQUser

        OAuthQQUser.objects.create(openid = openid,user = user)

        #状态保持
        from django.contrib.auth import login
        login(request,user)

        #设置cookie
        response = JsonResponse({'code':0,'errmsg':'ok'})

        response.set_cookie('username',user.username,max_age=14 *24 *3600)

        return response


